<!--
 * @Author: yangmy
 * @Date: 2022-03-10 18:06:33
 * @FileDescription:本期价格
-->
<template>
  <div class="left-lower">
    <com-box :title="title" class="com-box-title">
      <template #titleRight>
        <slot name="titleRight" />
      </template>
      <template #titleLeft>
        <div class="time time-fixed">
          <p>{{ unit[0] }}</p>
          <p>{{ unit[1] }}</p>
        </div>
      </template>
      <loading v-show="loading" />
      <!-- <div class="Price-unit-time Price-unit-time-relative">
        <div class="time time-fixed">
          <p>{{ unit[0] }}</p>
        </div>
      </div>
      <div class="Price-unit-time">
        <div class="time time-fixed">
          <p>{{ unit[1] }}</p>
        </div>
      </div> -->
      <div class="box-lower">
        <div class="Header">
          <span v-if="header.goodsName">{{ header.goodsName }}</span>
          <span v-if="header.avgPrice">{{ header.avgPrice }}</span>
          <span v-if="header.avgPriceThree">{{ header.avgPriceThree }}</span>
          <span v-if="header.avgPriceFive">{{ header.avgPriceFive }}</span>
          <span v-if="header.avgPriceTwo">{{ header.avgPriceTwo }}</span>
          <!-- <span>{{ header.avgPriceFour }}</span> -->
        </div>
        <div class="main">
          <el-scrollbar
            height="606px"
            ref="scrollbar"
            @scroll="handleScroll"
            @mouseover="stopScroll"
            @mouseout="startScroll"
          >
            <ul>
              <li
                v-for="(item, index) in CurrentPriceList"
                :key="index"
                @click="
                  onChoice(item.goodsName, item.goodsCode, index, item.unit)
                "
                class="tbody"
              >
                <span
                  v-if="item.goodsName"
                  :class="index == categoryIndex ? 'name-box' : 'name'"
                >
                  {{ item.goodsName }}
                  <div class="name-unit" v-if="item.unit !== '元/500克'">
                    {{ item.unit }}
                  </div>
                </span>
                <span v-if="header.avgPrice">
                  <p>{{ item.avgPrice }}</p>
                  <p
                    :class="
                      item.avgPriceD2D
                        ? item.avgPriceD2D.indexOf('+') != -1
                          ? 'red'
                          : parseFloat(item.avgPriceD2D) == 0
                          ? ''
                          : 'green'
                        : ''
                    "
                  >
                    {{ item.avgPriceD2D }}
                  </p>
                </span>
                <span v-if="header.avgPriceThree">
                  <p>{{ item.avgPriceThree }}</p>

                  <p
                    :class="
                      item.avgPriceD2DThree
                        ? item.avgPriceD2DThree.indexOf('+') != -1
                          ? 'red'
                          : parseFloat(item.avgPriceD2DThree) == 0
                          ? ''
                          : 'green'
                        : ''
                    "
                  >
                    {{ item.avgPriceD2DThree }}
                  </p>
                </span>
                <span v-if="header.avgPriceFive">
                  <p>{{ item.avgPriceFive }}</p>

                  <p
                    :class="
                      item.avgPriceD2DFive
                        ? item.avgPriceD2DFive.indexOf('+') != -1
                          ? 'red'
                          : parseFloat(item.avgPriceD2DFive) == 0
                          ? ''
                          : 'green'
                        : ''
                    "
                  >
                    {{ item.avgPriceD2DFive }}
                  </p>
                </span>
                <span v-if="header.avgPriceTwo">
                  <p>{{ item.avgPriceTwo }}</p>

                  <p
                    :class="
                      item.avgPriceD2DTwo
                        ? item.avgPriceD2DTwo.indexOf('+') != -1
                          ? 'red'
                          : parseFloat(item.avgPriceD2DTwo) == 0
                          ? ''
                          : 'green'
                        : ''
                    "
                  >
                    {{ item.avgPriceD2DTwo }}
                  </p>
                </span>
              </li>
            </ul>
          </el-scrollbar>
        </div>
      </div>
    </com-box>
  </div>
</template>
<script lang="ts">
import {
  defineComponent,
  reactive,
  toRefs,
  ref,
  onMounted,
  onBeforeUnmount,
  watch
} from 'vue'
import comBox from '@/components/comBox/comBox.vue'
import loading from '@/charts/loading.vue'
import httpRequest from '@/service'
interface IMenuData {
  goodsName: string
  goodsCode: string
  avgPrice: string
  avgPriceTwo: string
  avgPriceThree: string
  avgPriceFour?: string
  avgPriceD2D: string
  avgPriceD2DTwo: string
  avgPriceD2DThree: string
  avgPriceD2DFour?: string
}
interface IState {
  timerFlag: boolean
  time: string
  unit: string[]
  title: string
  header: any
  loading: boolean
  CurrentPriceList: any[]
  categoryIndex: number
  timer: any
  getData: (data?: string) => void
}

export default defineComponent({
  name: 'leftLower',
  props: {
    adcode: {
      type: String,
      default: ''
    },
    goodsIds: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: ''
    }
  },
  components: {
    comBox,
    loading
  },
  setup(props, { emit }) {
    const state: IState = reactive({
      timerFlag: true,
      time: '',
      unit: [],
      title: '',
      loading: false,
      header: {}, //表头
      CurrentPriceList: [],
      categoryIndex: 0,
      timer: null,
      getData: (data) => {
        state.loading = true
        httpRequest
          .get({
            url: 'M2P1bqjg',
            params: { adcode: props.adcode, goodsId: props.goodsIds }
          })
          .then((res) => {
            if (res.code == 200) {
              state.title = res.title
              state.time = res.time
              state.unit = res.unit.split(',')
              state.CurrentPriceList = res.data.map((item: any) => {
                const {
                  avgPrice,
                  avgPriceTwo,
                  avgPriceD2D,
                  avgPriceD2DTwo,
                  avgPriceD2DFive
                } = item
                if (
                  avgPrice ||
                  avgPriceTwo ||
                  avgPriceD2D ||
                  avgPriceD2DTwo ||
                  avgPriceD2DFive
                ) {
                  return {
                    ...item
                  }
                } else {
                  return item
                }
              })
              if (data === 'show') {
                emit(
                  'change',
                  res.data[0].goodsCode,
                  res.data[0].goodsName,
                  res.data[0].unit
                )
              }
              let exeNo = ''
              state.header = {}
              Object.keys(res.map).forEach((item) => {
                state.header[item] = ''
                if (res.map[item].indexOf(',') > -1) {
                  state.header[item] =
                    res.map[item].split(',')[0] +
                    '\n' +
                    res.map[item].split(',')[1]

                  !res.map[item].split(',')[1].includes('-') &&
                    (exeNo = res.map[item].split(',')[1])
                } else {
                  state.header[item] = res.map[item]
                }
                // 监测价格 => 超市价格
                if (state.header[item].includes('监测价格')) {
                  state.header[item] = state.header[item].replace(
                    '监测价格',
                    '超市价格'
                  )
                }
              })
              /**
               * 超市价格 => 农贸价格
               *
               * 日期 => 期号
               * 下面的数值：
               *    超市价格 + 批发价格 去平均值
               *
               */
              for (const key in state.header) {
                if (
                  state.header[key].includes('\n') &&
                  state.header[key].includes('-')
                ) {
                  state.header[key] = '农贸价格\n' + exeNo
                }
              }
            }
            state.loading = false
          })
          .catch(() => {
            state.loading = false
            console.log('请求失败')
          })
      }
    })

    const scrollbar = ref()
    let curScrollTop = 0
    onMounted(() => {
      onScroll()
    })
    const handAvgPrice = (a: string, b: string, type: '1' | '2') => {
      if (type == '2') {
        let aNum = parseFloat(a)
        let bNum = parseFloat(b)
        if (isNaN(aNum) || aNum == 0 || !a) {
          return isNaN(bNum) ? '0%' : b
        } else if (isNaN(bNum) || bNum == 0 || !b) {
          return isNaN(aNum) ? '0%' : a
        } else {
          let sum = (aNum * 0.01 + bNum * 0.01) / 2 / 0.01
          return `${sum > 0 ? '+' : ''}` + sum.toFixed(2) + '%'
        }
      } else {
        if (!a) {
          return b
        } else if (!b) {
          return a
        } else {
          return ((Number(a) + Number(b)) / 2).toFixed(2)
        }
      }
    }

    const onScroll = () => {
      state.timer = setInterval(() => {
        if (state.timerFlag) {
          curScrollTop++
          scrollbar.value?.setScrollTop(curScrollTop)
        }
        if (curScrollTop - scrollbar.value.wrap$.scrollTop > 1) {
          curScrollTop = 0
        }
      }, 50)
    }

    const onChoice = (
      goodsName: string,
      goodsCode: string,
      index: number,
      unit: string
    ) => {
      emit('change', goodsCode, goodsName, unit)
      state.categoryIndex = index
    }

    const stopScroll = () => {
      state.timerFlag = false
    }
    const startScroll = () => {
      state.timerFlag = true
      curScrollTop = scrollbar.value.wrap$.scrollTop
    }
    // 滚动时触发
    const handleScroll = (pos: any) => {
      curScrollTop = pos.scrollTop
    }
    onBeforeUnmount(() => {
      clearInterval(state.timer)
    })
    watch(
      () => [props.adcode, props.goodsIds],
      ([adVal, goodVal]) => {
        if (!adVal) {
          return false
        }
        state.getData()
      }
    )
    watch(
      () => props.type,
      (newVal) => {
        const index = state.CurrentPriceList.findIndex(
          (i: any) => i.goodsName === newVal
        )
        if (index > -1) {
          state.categoryIndex = index
        }
      }
    )
    state.getData('show')
    const refreshData = () => {
      state.getData('show')
    }
    const {
      time,
      title,
      CurrentPriceList,
      categoryIndex,
      header,
      unit,
      loading
    } = toRefs(state)
    return {
      time,
      title,
      CurrentPriceList,
      categoryIndex,
      scrollbar,
      header,
      unit,
      loading,
      stopScroll,
      startScroll,
      handleScroll,
      onChoice,
      scroll,
      refreshData
    }
  }
})
</script>
<style lang="less" scoped>
@MX: 1.9; // 放大倍数
.left-lower {
  height: 435px * @MX;
  width: 465px * @MX;
  overflow: hidden;
}
.left-lower .com-box-title {
  ::v-deep(.com-header) {
    height: 40px * @MX;
  }
  ::v-deep(.title) {
    font-size: 20px * @MX;
    line-height: 45px * @MX;
    background-size: 264px * @MX 45px * @MX;
    flex: 0 0 264px * @MX;
  }
}
// 单位
.Price-unit-time {
  font-family: 'Microsoft YaHei';
  color: rgba(227, 246, 255, 0.902);
  text-align: left;
  font-weight: 600;
  font-size: 14px * @MX;
  line-height: 1.714;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  .time {
    width: 100%;
    // display: flex;
    // justify-content: space-between;
    // align-items: center;
    padding-left: 20px * @MX;
  }
  .unit {
    margin-left: 18px * @MX;

    p {
      font-size: 14px * @MX;
      text-align: left;
      color: rgb(70, 237, 232);
      font-family: 'Microsoft YaHei';
    }
  }
}
.time {
  align-content: center;
  font-family: 'Microsoft YaHei';
  font-size: 14px * @MX;
  color: rgb(70, 237, 232);
  font-weight: bold;
  margin-top: 15px * @MX;
  text-align: center;
}
.Price-unit-time-relative {
  position: relative;
  top: -8px * @MX;
}
ul {
  width: 100%;
  height: 100%;
  padding: 0 14px * @MX;
}
.tbody {
  display: flex;
  height: 50px * @MX;
  align-items: center;
  justify-content: space-around;
  cursor: pointer;
  span {
    width: 25%;
    text-align: center;
    p:nth-child(1) {
      margin-bottom: 4px * @MX;
    }
  }
  p {
    font-size: 16px * @MX;
    font-family: 'Microsoft YaHei';
    color: #fff;
    font-weight: bold;
  }

  .red {
    font-size: 14px * @MX;
    font-weight: 550;
    // color: rgb(255, 38, 38);
    // color: #f15e09;
    color: rgb(255, 38, 38);
  }
  .green {
    font-weight: 550;
    font-size: 14px * @MX;
    // color: #03f0b2;
    color: rgb(66, 255, 0);
  }
  .name-box {
    font-size: 14px * @MX;
    font-family: 'Microsoft YaHei';
    color: rgb(255, 192, 111);
    font-weight: bold;
  }
  .name-unit {
    font-size: 12px * @MX;
  }

  .name {
    font-size: 14px * @MX;
    font-family: 'Microsoft YaHei';
    color: #fff;
    font-weight: bold;
  }
  &:nth-child(even) {
    height: 54px * @MX;
    background-color: rgba(33, 122, 255, 0.2);
  }
  &:nth-child(odd) {
    width: 100%;
    height: 75px * @MX;
  }
}
.box-lower {
  margin: 0 auto;
  width: 95%;
  margin-top: 20px * @MX;
}
.Header {
  background-color: rgba(33, 122, 255, 0.4) !important;
  height: 46px * @MX;
  z-index: 416;
  display: flex;
  align-items: center;
  justify-content: space-around;
  span {
    width: 25%;
    white-space: pre-line;
    font-size: 14px * @MX;
    font-family: 'Microsoft YaHei';
    color: rgba(160, 220, 255, 0.902);
    font-weight: bold;
    line-height: 1.714;
    text-align: center;
  }
}
.main {
  height: calc(100% - 20px * @MX);
}
// ::v-deep(.el-scrollbar__wrap.el-scrollbar__wrap--hidden-default) {
//   overflow-y: scroll;
// }
</style>
